package com.ruoyi.media.publishRecord.controller;

import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.media.mediaAccount.domain.MediaAccount;
import com.ruoyi.media.mediaAccount.service.IMediaAccountService;
import com.ruoyi.media.publishModelConfig.domain.MediaPublishModelConfig;
import com.ruoyi.media.publishModelConfig.service.IMediaPublishModelConfigService;
import com.ruoyi.media.publishRecord.domain.MediaPublishRecord;
import com.ruoyi.media.publishRecord.domain.publish.PublishRes;
import com.ruoyi.media.utils.WxUtils;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.publishRecord.domain.vo.MediaPublishRecordVo;
import com.ruoyi.media.publishRecord.domain.bo.MediaPublishRecordBo;
import com.ruoyi.media.publishRecord.service.IMediaPublishRecordService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 视频号发布记录
 *
 * @author dqw
 * @date 2023-05-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/media/publishRecord")
public class MediaPublishRecordController extends BaseController {

    private final IMediaPublishRecordService iMediaPublishRecordService;

    private final IMediaAccountService iMediaAccountService;
    private final IMediaPublishModelConfigService mediaPublishModelConfigService;

    /**
     * 查询视频号发布记录列表
     */
    @SaCheckPermission("media:publishRecord:list")
    @GetMapping("/list")
    public TableDataInfo<MediaPublishRecordVo> list(MediaPublishRecordBo bo, PageQuery pageQuery) {
        return iMediaPublishRecordService.queryPageList(bo, pageQuery);
    }


    /**
     * 获取当前账号发布数据
     */
    @GetMapping("/getAccountPublishData/{username}")
    public R<?> getAccountPublishData(@PathVariable String username) {
        return R.ok(iMediaPublishRecordService.getAccountPublishData(username));
    }


    /**
     * 发布状态修改
     */
    @PostMapping("/updatePublishStatus")
    public void updatePublishStatus(@RequestBody PublishRes publishRes) {
        MediaPublishRecord mediaPublishRecord = iMediaPublishRecordService.getById(publishRes.getId());
        if(mediaPublishRecord != null){
            mediaPublishRecord.setPublishStatus(publishRes.getStatus()); //已发布
            mediaPublishRecord.setCoverLink(publishRes.getCoverLink());
            mediaPublishRecord.setVideoLink(publishRes.getVideoLink());
            mediaPublishRecord.setErrLog(publishRes.getErrLog());
            iMediaPublishRecordService.updateById(mediaPublishRecord);
        }
    }



    /**
     * 导出视频号发布记录列表
     */
    @SaCheckPermission("media:publishRecord:export")
    @Log(title = "视频号发布记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaPublishRecordBo bo, HttpServletResponse response) {
        List<MediaPublishRecordVo> list = iMediaPublishRecordService.queryList(bo);
        ExcelUtil.exportExcel(list, "视频号发布记录", MediaPublishRecordVo.class, response);
    }

    /**
     * 获取视频号发布记录详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("media:publishRecord:query")
    @GetMapping("/{id}")
    public R<MediaPublishRecordVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaPublishRecordService.queryById(id));
    }

    /**
     * 新增视频号发布记录
     */
    @SaCheckPermission("media:publishRecord:add")
    @Log(title = "视频号发布记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<String> add(@Validated(AddGroup.class) @RequestBody MediaPublishRecordBo bo) {
        if(bo.getMediaPublishRecordBos() != null && bo.getMediaPublishRecordBos().size() > 0){
            for(MediaPublishRecordBo item : bo.getMediaPublishRecordBos()) {
                MediaAccount mediaAccount = iMediaAccountService.getById(item.getId());
                LambdaQueryWrapper<MediaPublishModelConfig> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(MediaPublishModelConfig::getAccountId,item.getId());
                MediaPublishModelConfig mediaPublishModelConfig = mediaPublishModelConfigService.getOne(queryWrapper);

                //添加发布列表
                MediaPublishRecordBo mediaPublishRecordBo = new MediaPublishRecordBo();
                mediaPublishRecordBo.setNickname(mediaAccount.getNickname());
                mediaPublishRecordBo.setPlatformCode(mediaAccount.getPlatformCode());
                mediaPublishRecordBo.setHeadImgUrl(mediaAccount.getHeadImgUrl());
                mediaPublishRecordBo.setFilePath(mediaPublishModelConfig.getFilePath());
                mediaPublishRecordBo.setDescription(mediaPublishModelConfig.getDescription());
                mediaPublishRecordBo.setAccountId(String.valueOf(mediaPublishModelConfig.getAccountId()));
                iMediaPublishRecordService.insertByBo(mediaPublishRecordBo);
            }
        }else{
                //创建主键
                String id = WxUtils.getRandomNumberByTime();
                MediaAccount mediaAccount = iMediaAccountService.getById(bo.getAccountId());
                //将当前账号的参数复制到对应属性
                bo.setId(Long.parseLong(id));
                bo.setNickname(mediaAccount.getNickname());
                bo.setPublishTime(bo.getEffectiveTime());
                bo.setPlatformCode(mediaAccount.getPlatformCode());
                bo.setHeadImgUrl(mediaAccount.getHeadImgUrl());
                iMediaPublishRecordService.insertByBo(bo);
                return R.ok(id);
        }
        return R.ok();
    }



    /**
     * 修改视频号发布记录
     */
    @SaCheckPermission("media:publishRecord:edit")
    @Log(title = "视频号发布记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaPublishRecordBo bo) {
        return toAjax(iMediaPublishRecordService.updateByBo(bo));
    }

    /**
     * 删除视频号发布记录
     *
     * @param ids 主键串
     */
    @SaCheckPermission("media:publishRecord:remove")
    @Log(title = "视频号发布记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
       List<Long> dataList =  Arrays.asList(ids);
       for(Long id : dataList){
           MediaPublishRecord mediaPublishRecord = iMediaPublishRecordService.getById(id);
           mediaPublishRecord.setDelFlag(1);
           iMediaPublishRecordService.updateById(mediaPublishRecord);
       }
        return toAjax(true);
    }
}
